package view;

import controller.CartController;
import controller.GoodsController;
import controller.OrderController;
import controller.UserController;
import dao.AddressDao;
import dao.CartDAO;
import dao.impl.AddressDaoImpl;
import dao.impl.CartDAOImpl;
import dao.impl.GoodsDAOImpl;
import model.Address;
import model.Goods;
import model.Order;
import model.User;
import model.common.Entity;
import model.common.Msg;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.JSONUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class OrderClient extends Client {

    private double count_price;

    private String pay_money;

    private final OrderController orderController;

    private final GoodsDAOImpl goodsDAO;

    private final UserController userController;
    private final Order order;

    private final Goods goods;

    private final GoodsController goodsController;

    private UserService userService;

    private AddressDao addressDao;

    private CartDAO cartDAO;


    Map<String, Order> orderMap = new HashMap<>();

    public OrderClient() {
        orderController = new OrderController();
        userController = new UserController();
        order = new Order();
        goodsDAO = new GoodsDAOImpl();
        goods = new Goods();
        goodsController = new GoodsController();
        UserServiceImpl userService = new UserServiceImpl();
        addressDao = new AddressDaoImpl();
        cartDAO = new CartDAOImpl();
    }

    public String index() {
        String result = userOperate("请选择操作", "1:查看订单列表", "2:删除订单", "3:订单详情");
        while (true) {
            if ("1".equals(result)) {
                findMyOrder();
                break;
            } else if ("2".equals(result)) {
                findMyOrder();
                deleteOrder();
                break;
            } else if ("3".equals(result)) {
                showOrderDetails();
                break;
            }
        }
        return ORDER;
    }

    public String generateOrder() {
        User loginUser = userController.getLoginUser();
        String consignee = loginUser.getUsername();
        Address userDefaultAddress = addressDao.getUserDefaultAddress(loginUser);
        String consigneeAddress;
        System.out.println("test");
        // 没有默认收货地址就输入收货地址
        if (null == userDefaultAddress) {
            System.out.println("请输入你的收货地址:");
            consigneeAddress = sc.next();
        } else {
            // 设置为默认收货地址
            consigneeAddress = userDefaultAddress.getAddress();
        }

        String phone;
        if (null == loginUser.getPhone()) {
            System.out.println("请输入你的电话号码:");
            phone = sc.next();
        } else {
            phone = loginUser.getPhone();
        }

        System.out.println("================订单生成中=====================");
        order.setConsignee(consignee);
        order.setSerialNumber(Entity.getUUID()); //设置编号
        order.setUserId(userController.getLoginUser().getId());  //设置用户id
        order.setConsigneeAddress(consigneeAddress); //设置家庭住址
        order.setPhone(phone); //设置电话号码
        for (Map.Entry<String, Integer> entry : CartController.getCart().entrySet()) {   // 遍历购物车 计算价格
            count_price += goodsDAO.getGoodsById(entry.getKey()).getPrice() * entry.getValue();
        }

        order.setAmount(count_price); // 设置订单总价格
        order.setCreateTime(new Date());
        order.setState("WAITING_PAY");
        System.out.println("订单已生成");
        System.out.println("订单号:" + order.getSerialNumber());
        System.out.println("总金额:" + count_price);
        System.out.println("状态:" + order.getState());

        orderController.addOrder2Db(order);
        payOrder();
        return ORDER;
    }


    public void payOrder() {
        if (order.getAmount() > userController.getLoginUser().getBalance()) {
            System.out.println("用户余额不足，结算失败");
            return;
        }

        for (Map.Entry<String, Integer> entry : CartController.getCart().entrySet()) {   //
            Goods good = goodsDAO.getGoodsById(entry.getKey());
            if ((good.getNumber() - entry.getValue()) <= 0) {
                goods.setNumber(0);
                System.out.println("结算失败 " + good.getName() + "库存不足");
                return;
            } else {
                goods.setNumber(good.getNumber() - entry.getValue());
            }
            goods.setId(good.getId());
            goods.setCreateTime(good.getCreateTime());
            goods.setDeleteTime(good.getDeleteTime());
            goods.setIsDel(good.getIsDel());
            goods.setName(good.getName());
            goods.setPrice(good.getPrice());
            goods.setBrand(good.getBrand());
            goodsController.updateGoodsById(entry.getKey(), goods);
        }

        // 写入订单详情表
        for (Map.Entry<String, Integer> entry : CartController.getCart().entrySet()) {   // 遍历购物车 计算价格
            Goods good = goodsDAO.getGoodsById(entry.getKey());
            System.out.println(good);
            orderController.addOrderDetail(order, good, entry.getValue());
        }

        // 清空当前用户购物车
        cartDAO.deleteTrolleyAll(userController.getLoginUser().getId());


    }

    public void showOrderDetails() {

        GoodsDAOImpl goodsDAO = new GoodsDAOImpl();
        System.out.println(".\t\t" + "商品名称" + "\t\t" + "数量" + "\t\t" + "价格");
        for (Map.Entry<String, Integer> entry : CartController.getCart().entrySet()) {
            System.out.println(".\t\t" + goodsDAO.getGoodsById(entry.getKey()).getName() + "\t\t\t" +
                    entry.getValue() + "\t\t" +
                    goodsDAO.getGoodsById(entry.getKey()).getPrice());
        }

    }


    public void deleteOrder() {
        findMyOrder();
        String result = userOperate("请输入序号删除订单", "I:返回首页");
        Order order = orderMap.get(result);
        orderController.deleteOrder(order.getId());
        System.out.println("删除成功");
    }

//    public void showOrderList(){
//        String msg = orderController.findOrder();
//        Msg msgObj = JSONUtil.JSON2Entity(msg, Msg.class);
//        Object obj = msgObj.getObj();   // [{}，{}]
//        List<?> orderListObj = (List<?>)obj;
//        System.out.println("【订单列表】");
//        System.out.println("\t\t\t\t\t\t编号\t\t\t\t\t\t金额\t\t\t\t\t\t创建时间\t\t\t\t收货人\t\t收货地址");
//        System.out.println("---------------------------");
//        int index = 1; //编号
//        for (Object o : orderListObj){
//            String ordersJson = o.toString();
//            Order order = JSONUtil.JSON2Entity(ordersJson, Order.class);
//            String serial = order.getSerialNumber();
//            double price = order.getAmount();
//            String create_time = order.getCreateTime().toString();
//            String consignee = order.getConsignee();
//            String consigneeAddress = order.getConsigneeAddress();
//            System.out.println(index + "\t\t" + serial + "\t\t" + price + "\t\t" + create_time +
//                    "\t\t" + consignee + "\t\t" + consigneeAddress);
//            orderMap.put(index+"", order);
//            index ++;
//        }
//    }

    public void findMyOrder() {
        // 传入当前用户id
        String msg = orderController.findMyOrder(userController.getLoginUser().getId());
        Msg msgObj = JSONUtil.JSON2Entity(msg, Msg.class);
        Object obj = msgObj.getObj();   // [{}，{}]
        List<?> orderListObj = (List<?>) obj;
        System.out.println("【订单列表】");
        System.out.println("\t\t\t\t\t\t编号\t\t\t\t\t\t金额\t\t\t\t\t\t创建时间\t\t\t\t收货人\t\t收货地址");
        System.out.println("---------------------------");
        int index = 1; //编号
        for (Object o : orderListObj) {
            String ordersJson = o.toString();
            Order order = JSONUtil.JSON2Entity(ordersJson, Order.class);
            String serial = order.getSerialNumber();
            double price = order.getAmount();
            String create_time = order.getCreateTime().toString();
            String consignee = order.getConsignee();
            String consigneeAddress = order.getConsigneeAddress();
            System.out.println(index + "\t\t" + serial + "\t\t" + price + "\t\t" + create_time +
                    "\t\t" + consignee + "\t\t" + consigneeAddress);
            orderMap.put(index + "", order);
            index++;
        }
    }

}
